import React, { useCallback, useEffect, useRef, useState } from "react";

const INIT_VALUE = 0;
const TIMER = 5000;

const CounterComponent = () => {
  const [count, setCount] = useState(INIT_VALUE);
  const timerRef = useRef(null);

  const clearTimer = useCallback(() => {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
    }
  }, [timerRef]);

  useEffect(() => {
    return clearTimer;
  }, [clearTimer]);

  const setTimer = useCallback(() => {
    clearTimer();
    timerRef.current = setTimeout(() => {
      setCount(INIT_VALUE);
    }, TIMER);
  }, [setCount, timerRef, clearTimer]);

  const addCount = useCallback(() => {
    setTimer();
    setCount((v) => v + 1);
  }, [setTimer, setCount]);

  return (
    <div>
      <div>{count}</div>
      <button onClick={addCount}>add</button>
    </div>
  );
};

export default CounterComponent;
